package cn.autumnorange.user.entity;

import cn.autumnorange.commons.util.StringUtils;
import cn.autumnorange.dto.UserDetailDto;
import cn.autumnorange.user.entity.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service(value = "userDetailsServiceImpl")
public class UserDetailsServiceImpl {
  @Autowired
  private AdminRepository adminRepository;

  @Transactional(readOnly = true)
  public UserDetailDto loadUserByUsername(String s) throws UsernameNotFoundException {
    UserDetailDto userDto = null;

    userDto = adminRepository.findAdminEntityByUserName(s).createUserDetailDto();

    return userDto;
  }


  public void saveAdmin(AdminEntity adminEntity) throws UsernameNotFoundException {
    if (StringUtils.trimToNull(adminEntity.getId()) == null) {
      adminEntity.setId(UUID.randomUUID().toString());
    }
      adminEntity.setPassword(new BCryptPasswordEncoder().encode(adminEntity.getPassword()));
    adminRepository.save(adminEntity);
  }
}
